from rest_framework import serializers

from goods.models import SKU
from user.models import User
import re
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework_jwt.settings import api_settings
from django.conf import settings
from django.core.mail import send_mail
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from celery_tasks.email.tasks import send_email

'''
 	username	str	是	用户名
 	password	str	是	密码
 	password2	str	是	确认密码
 	sms_code	str	是	短信验证码
 	mobile	str	是	手机号
 	allow	str	是	是否同意用户协议
'''


class UserSerializer(serializers.ModelSerializer):
    # 显示指明验证字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)  #
    token = serializers.CharField(read_only=True)  # 添加token　进行序列化返回

    class Meta:
        model = User
        fields = ('id', 'mobile', 'username', 'password', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '名字过长',
                    'min_length': '名字过短'
                }
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    'max_length': '密码过长',
                    'min_length': '密码过短'
                }
            }

        }

    # 判断手机格式
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不正确')

        return value

    # 判断是否选中协议
    def validate_allow(self, value):

        if value != 'true':
            raise serializers.ValidationError('未选中')

        return value

    def validate(self, attrs):
        # 密码判断
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('密码不一致')

        # 判断短信
        # 1 先获取缓存中的短信
        conn = get_redis_connection('verify')
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])

        if not real_sms_code:
            raise serializers.ValidationError('短信验证码失效')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):

        print(validated_data)
        # 删除不需要保存的字段数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        print(validated_data)

        user = super().create(validated_data)

        # 名文密码加密
        user.set_password(validated_data['password'])
        user.save()

        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 写入token
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        # validated_data 验证后的数据　　instance　返回的user对象
        instance.email = validated_data['email']
        instance.save()

        # 用户数据加密
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'id': instance.id, 'username': instance.username}).decode()

        # 发送邮件
        # send_mail('美多商城邮箱验证','',settings.EMAIL_FROM,['fengweihao77@163.com'],html_message='<a href="www.itcast.cn">传智播客</a>')
        send_email.delay(token, validated_data['email'])

        return instance


class VerifyEmailSerializer(serializers.Serializer):
    token = serializers.CharField(write_only=True)

    def validate(self, attrs):

        # 　token解密
        tjs = TJS(settings.SECRET_KEY, 300)

        try:
            data = tjs.loads(attrs['token'])
        except:
            raise serializers.ValidationError('错误的token')

        if not data:
            raise serializers.ValidationError('无效的token')

        attrs['data'] = data
        return attrs


class AddUserBrowsingHistorySerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    # 验证id商品是否存在
    def validate(self, attrs):

        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

    def create(self, validated_data):

        user = self.context['request'].user
        sku_id = validated_data['sku_id']

        # 建立redis连接
        conn = get_redis_connection('history')
        pl = conn.pipeline()
        # 删除重复数据

        pl.lrem('history_%s' % user.id, 0, sku_id)
        # 写入数据
        pl.lpush('history_%s' % user.id, sku_id)
        # 控制数量
        pl.ltrim('history_%s' % user.id, 0, 4)

        pl.execute()

        return validated_data
